<template>
  <div>
    <el-upload
      action="/api/xcx/upload"
      :data="uploadData"
      accept="image/*"
      :file-list.sync="imgList"
      :on-success="handleUploadSuccess"
      :on-remove="handleRemove"
    >
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">同一个栏目的图片高度需一致</div>
    </el-upload>

    <div v-for="(opera, operaIndex) in activeImg" :key="opera.uid">
      <cascader 
        :category-list="categoryList" 
        :opera.sync="opera"
        :opera-index="operaIndex"/>
    </div>
    
  </div>
</template>

<script>
import Cascader from './coms/Cascader';

export default {
  components: {
    Cascader
  },
  props: {
    categoryList: Array,
    currentData: Array
  },
  data() {
    return {
      uploadData: { not_checklogin: 1 },
      imgList: this.currentData,
      options: [
        { value: 'contact', label: '客服' },
        { value: 'others', label: '其他' },
        { value: 'category', label: '分类', children: this.categoryList }
      ]
    };
  },
  watch: {
    imgList(value) {
      this.$emit('currentRowChanged', value);
    }
  },
  computed: {
    activeImg() {
      return this.imgList.filter(item => item);
    }
  },
  created() {
    this.getGoodList(this.category, false);
  },
  methods: {
    handleUploadSuccess(response, file) {
      const { data } = response;
      const { url } = data;
      const name = data.file_name;
      const uid = data.id;
      this.imgList.push({ url, name, uid });
    },
    handleRemove(file, fileList) {
      this.imgList = fileList;
    },
    getGoodList(id, change = true) {
      if (change) this.goods = [];
      if (!id) return;
      const target = this.categoryList.find(item => item.value === id);
      if (target.children) {
        this.options = target.children;
      } else {
        this.fetchGoodList(id);
      }
    },
    fetchGoodList(id) {
      return axios
        .get(`https://nihaocai.zkong.me/api/categories/${id}`)
        .then(res => res.data.data.goods.map(item => this.genGood(item)))
        .then(goodList => {
          this.options = goodList;
          this.$emit('assertGoodList', id, goodList);
        });
    },
    genGood({ id, name, image, sale_price, unit, attributes_by_status }) {
      return {
        value: id,
        label: name,
        image: `${image}?x-oss-process=image/resize,m_pad,h_100,w_100`,
        price: sale_price,
        unit,
        attr: attributes_by_status || [],
        cate: this.category
      };
    }
  }
};
</script>

<style scoped>

</style>
